package org.example.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.auth.service.SysUserRoleService;
import org.example.model.system.SysRole;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.auth.mapper.SysRoleMapper;
import org.example.auth.service.SysRoleService;
import org.example.model.system.SysUserRole;
import org.example.vo.system.AssginRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysRoleServiceImp extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
//    查询所有的角色和当前用户所属角色


    @Autowired
    private SysUserRoleService sysUserRoleService;


    @Override
    public Map<String, Object> findRoleService(long userId) {
        //1：查询所有的角色，返回list集合 返回
       List<SysRole> allRoleList=   baseMapper.selectList(null);
// 2 根据userId来查询角色用户关系表，查询userid对应的角色id
        LambdaQueryWrapper<SysUserRole> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,userId);
    List<SysUserRole> existUserRoleList=sysUserRoleService.list(wrapper);
//从我们查询出来的用户的id对应的角色list集合，获取角色id
   List<Long>    existRoleIdList =existUserRoleList.stream().map(c->c.getRoleId()).collect(Collectors.toList());

//  3 根据查询出来的所有角色id，找到对应的信息，
//    根据角色id到所有的角色的list集合进行比较
        List<SysRole> assignRoleList=new ArrayList<>();
        for (SysRole sysRole:allRoleList){
//            比较
            if (existRoleIdList.contains(sysRole.getId())){
                assignRoleList.add(sysRole);
            }
        }
        //    4把得到的两部分的数据进行封装map集合，返回
        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("assginRoleList", assignRoleList);
        roleMap.put("allRolesList", allRoleList);
        return roleMap;
    }



//    为用户分配角色
    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {

//        把用户之前分配的角色数据进行删除，用户关系表里面，根据userid删除
        LambdaQueryWrapper<SysUserRole>wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,assginRoleVo.getUserId());
        sysUserRoleService.remove(wrapper);
//        重新分配
        List<Long> roleIdList=assginRoleVo.getRoleIdList();
        for (Long roleId:roleIdList){
            if (StringUtils.isEmpty(roleId)){
                continue;
            }
            SysUserRole sysUserRole=new SysUserRole();
            sysUserRole.setUserId(assginRoleVo.getUserId());
            sysUserRole.setRoleId(roleId);
            sysUserRoleService.save(sysUserRole);
        }

    }
//    @Autowired
//    private SysRoleMapper sysRoleMapper;

}
